package io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 对象序列化文件工具类
 * @Author 左龙龙
 * @Date 21-6-30
 * @Version 1.0
 **/
public class ObjectFileUtil {

    /**
     * 对象保存到文件中
     *
     * @param o
     * @param file
     */
    public static void saveObjToFile(Object o, File file) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(o);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从文件中读出对象
     *
     * @param file
     * @return
     */
    public static Object readObjFromFile(File file) {
        if(file == null || !file.exists()){
            return null;
        }

        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) {
        File file = new File("users.data");


        List<User> users = new ArrayList<User>();
        users.add(new User("张三", "111", 12, "男"));
        users.add(new User("李四", "222", 12, "女"));
        // 对象序列化到文件
        ObjectFileUtil.saveObjToFile(users, file);

        // 文件读取序列化对象
        users = (List<User>) ObjectFileUtil.readObjFromFile(file);
        for(User user : users){
            System.out.println(user.toString());
        }
    }
}
